﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SqlCon;
using System.Collections;

namespace yfxt
{
    public partial class gl_pdlr : Form
    {
        public gl_pdlr()
        {
            InitializeComponent();
        }

        string comStr;
        int var_a = 0;
        int huizong = 0;   //   0为屏蔽汇总代码（从Yf_KCMX插数据入datagridView1的）
        int kaishipandian = 0; //盘点标志 0为未盘点，1为开始盘点  
        ArrayList lishi_a = new ArrayList();   //获取历史盘点单号
        ArrayList lishi_b = new ArrayList();   //获取盘点状态 0为已保存 1为已完成
        int shifouzengjiayihang = 0;   //有盘点单&& 没有保存状态的盘点单情况下，1为datagridView2增加一行
        int pingbi = 0;    //当pingbi=1 datagridView2点击历史盘点单不触发事件
        string pddh="";    //盘点单号（新单||已保存状态单号）
        string ypmc_2 = "";    //中间变量，用于搜索完在datagridView1中定位焦点

        private void gl_pdlr_Load(object sender, EventArgs e)
        {
            //dataGridView1.Rows.Add(5);
            dataGridView1.AllowUserToResizeRows = false;                     //禁止用鼠标调整datagridView单元格的大小。
            dataGridView1.AllowUserToResizeColumns = false;
            dataGridView2.AllowUserToResizeRows = false;                     //禁止用鼠标调整datagridView单元格的大小。
            dataGridView2.AllowUserToResizeColumns = false;
            foreach (DataGridViewColumn c in dataGridView1.Columns)        //禁止对datagridView列进行排序
            {
                c.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            foreach (DataGridViewColumn c in dataGridView2.Columns)        //禁止对datagridView列进行排序
            {
                c.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            comStr = "select pdrq,pddh,pdwc from YF_YK01 order by pdwc desc,pdrq";
            DataTable dt2 = new DataTable();
            dt2.Load(SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null));

            lishi_a.Clear();
            lishi_b.Clear();
            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                lishi_a.Add(dt2.Rows[i][1].ToString());
                lishi_b.Add(dt2.Rows[i][2].ToString());
                dataGridView2.Rows.Add(1);
                dataGridView2.Rows[i].Cells[0].Value = Convert.ToDateTime(dt2.Rows[i][0]).ToString("yyyy-MM-dd").Replace('-', '.');
            }

            #region datagridView2 显示时间数据  是否新增一行
            if (dt2.Rows.Count < 1)                                            //没盘点单的情况，增加一行
            {
                dataGridView2.Rows.Add(1);
                dataGridView2.Rows[dataGridView2.Rows.Count - 1].Cells[0].Value = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd").Replace('-', '.');
                //显示盘点日期、盘点状态、完成时间、操作人   ---新单
                label5.Text = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd").Replace('-', '.');
                label6.Text = "未保存";
                label7.Text = "          ";
                comStr = "select t.ygxm from GY_YGDM t where t.ygbh='" + Program.ygbh + "'";
                label8.Text = (SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null)).ToString();
            }
            if (dt2.Rows.Count>0)  //for (int i = 0; i < dt2.Rows.Count; i++)  //有盘点单的情况
            {
                if (dt2.Rows[dt2.Rows.Count-1][2].ToString() != "1")   //有已保存状态的盘点单，存在便执行代码
                {                   
                    //显示盘点日期、盘点状态、完成时间、操作人    ---已保存的盘点单
                    comStr = "select t2.pdrq,t2.wcrq,t.ygxm from GY_YGDM t,YF_YK01 t2 where t.ygbh='" + Program.ygbh + "' "+
                        "and t2.yfsb='" + mainform.yfsb + "' and t2.pddh='" + lishi_a[dataGridView2.CurrentRow.Index]+ "'";
                    DataTable dt5 = new DataTable();
                    dt5.Load(SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null));  //dt5只有一行数据
                    label5.Text = Convert.ToDateTime(dt5.Rows[0][0]).ToString("yyyy-MM-dd").Replace('-', '.');                  
                    label6.Text = "已保存";
                    label7.Text = "          ";
                    label8.Text = dt5.Rows[0][2].ToString();

                    dataGridView2_CellClick(null,null);//tiaojian_huizong(); 触发dataGridView2_CellClick事件

                    shifouzengjiayihang = 1;
                }                
                if (shifouzengjiayihang == 0)    //无保存状态的盘点单，增加一行
                {
                    dataGridView2.Rows.Add(1);
                    dataGridView2.Rows[dataGridView2.Rows.Count - 1].Cells[0].Value = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd").Replace('-', '.');
                    //显示盘点日期、盘点状态、完成时间、操作人   ---新单
                    label5.Text = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd").Replace('-', '.');
                    label6.Text = "未保存";
                    label7.Text = "          ";
                    comStr = "select t.ygxm from GY_YGDM t where t.ygbh='" + Program.ygbh + "'";
                    label8.Text = (SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null)).ToString();

                    //dataGridView2_CellClick(null, null);//tiaojian_huizong(); 触发dataGridView2_CellClick事件
                }
            }
            #endregion            

            #region datagridView默认不选中单元格，使之成蓝色
            if (dataGridView1.Rows.Count > 0)
            {
                dataGridView1.Rows[0].Selected = false;
            }
            //datagridView默认选中最后一行
            dataGridView2.Rows[0].Selected = false;
            dataGridView2.Rows[dataGridView2.Rows.Count - 1].Selected = true;
            #endregion
        }

        /// <summary>
        /// 关闭按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {
            this.Close();

        }     
   
        /// <summary>
        /// 汇总按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //datagridView只读
            
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {                
                dataGridView1.Rows[i].Cells[9].Value="0";
                dataGridView1.Rows[i].Cells[8].Value = "0";
            }
            huizong = 1;
            tiaojian_huizong();
            button1.Enabled = false;
            button4.Enabled = true;
        }

        /// <summary>
        /// 开始盘点按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            dataGridView1.Columns[8].ReadOnly = false;
            dataGridView1.Columns[0].ReadOnly = false;
            //this.Show();
            //dataGridView1.Focus();
            dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[8];
            kaishipandian = 1;
            pingbi = 1;
            button4.Enabled = false;
            button5.Enabled = true;
        }

        /// <summary>
        /// 保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否保存盘点单？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                if (pddh=="")
	            { 
        		     pddh="100001";
	            }
                else
	            {
                    comStr = "delete YF_YK01 where pddh='"+pddh+"';delete YF_YK02 where pddh='"+pddh+"'";
                    SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null);
	            }
                comStr = "insert into YF_YK01(yfsb,pddh,pdrq,czgh,pdwc) values ('"+mainform.yfsb+"','"+pddh+"','"+label5.Text.ToString()+"','"+Program.ygbh+"','0')";
                SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null);
                
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
			    {
                    comStr = "insert into YF_YK02(sbxh,yfsb,pddh,ypph,ypxh,ypgg,yfdw,ypcd,lsjg,pqsl,spsl,pd_flag) select max(sbxh)+1,'"+mainform.yfsb+"','"+pddh+"',"+
                        "'"+dataGridView1.Rows[i].Cells[1].Value.ToString()+"',t2.ypxh,'"+dataGridView1.Rows[i].Cells[3].Value.ToString()+"',"+
                        "t3.ypcd,'"+dataGridView1.Rows[i].Cells[6].Value.ToString()+"','"+dataGridView1.Rows[i].Cells[7].Value.ToString()+"',"+
                        "'"+dataGridView1.Rows[i].Cells[9].Value.ToString()+"','"+dataGridView1.Rows[i].Cells[0].Value.ToString()+"' "+
                        "from YF_YK02 t,yk_typk t2,YK_CDDZ t3 where t.ypxh=t1.ypxh and t3.ypmc='"+dataGridView1.Rows[i].Cells[5].Value.ToString()+"' "+
                        "and t.ypmc='"+dataGridView1.Rows[i].Cells[2].Value.ToString()+"'";
                    SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null);
			    } 
                
              label6.Text="已保存";
              label5.Enabled=false;
              label6.Enabled=true;
              MessageBox.Show("盘点单已完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
          
        }

        /// <summary>
        /// CheckBoxColumn 勾选，改变行的颜色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    if (dataGridView1.CurrentCell == dataGridView1.Rows[i].Cells[0] && dataGridView1.Columns[0].ReadOnly == false)
                    {
                        string re_value = dataGridView1.Rows[i].Cells[0].EditedFormattedValue.ToString();
                        if (re_value == "False")   //判断勾选的
                        {
                            if (MessageBox.Show("是否置为已盘标志？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                            {
                                dataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.PaleGoldenrod;
                            }
                        }
                        else
                        {
                            if (MessageBox.Show("该药品已盘点，是否取消盘点标志？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                            {
                                dataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.White;
                            }
                        }
                    }
                }
            }
        }        

        /// <summary>
        /// 实发数量的列总在编辑状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                //this.Show();
                if (dataGridView1.CurrentCell == dataGridView1.Rows[i].Cells[8])
                {
                    this.dataGridView1.BeginEdit(true);
                }
            }
        }

        /// <summary>
        /// 输入数量后，回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            if (kaishipandian==1)
            {
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    if (dataGridView1.Rows[i].Cells[8].Value!=null)   //防止单元格为null，**.ToString()报错
                    {
                        if (dataGridView1.CurrentCell == dataGridView1.Rows[i].Cells[8] && dataGridView1.Rows[i].Cells[8].Value.ToString() != "0")
                        {
                            dataGridView1.Rows[i].Cells[0].Value = true;                             //CheckBoxColumn 变成勾选状态
                            dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.PaleGoldenrod;  //单元格变颜色

                            int int1 = int.Parse(dataGridView1.Rows[i].Cells[9].Value.ToString());
                            int int2 = int1;
                            int1 += int.Parse(dataGridView1.Rows[i].Cells[8].Value.ToString());
                            dataGridView1.Rows[i].Cells[9].Value = int1;
                            if (dataGridView1.Rows[i].Cells[9].Value.ToString().Substring(0, 1) == "-")
                            {
                                dataGridView1.Rows[i].Cells[9].Value = int2;
                                MessageBox.Show("实盘数量不能小于0！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            dataGridView1.Rows[i].Cells[8].Value = "0";
                            //dataGridView1.CurrentCell = dataGridView1.Rows[i + 1].Cells[8];  //不明白这样代码为什么会报错
                        }  
                    }                   
                }
            }           
        }

        #region   datagridView只能输出数字 winform下c#实现datagridview单元格只能输出数字,"02"还不能屏蔽输入
        /// 自定义事件
        private void Cells_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar < '0' || e.KeyChar > '9') && e.KeyChar != '\b' && e.KeyChar != (char)45)
            {
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    if (dataGridView1.CurrentCell == dataGridView1.Rows[i].Cells[8])
                    {
                        e.Handled = true;
                    }
                }
            }
        }
        public DataGridViewTextBoxEditingControl CellEdit = null; // 声明 一个 CellEdit   
        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {

            CellEdit = (DataGridViewTextBoxEditingControl)e.Control;
            CellEdit.SelectAll();
            CellEdit.KeyPress += Cells_KeyPress;
        }
        #endregion

        /// <summary>
        /// 按条件，汇总函数
        /// </summary>
        private void tiaojian_huizong()
        {
            DataTable dt = new DataTable();
            if (var_a == 0)
            {
                comStr = "select t.ypph,t1.ypmc,t1.yfgg,t1.yfdw,t2.cdqc,t.lsjg,t.ypsl from Yf_KCMX t,yk_typk t1,YK_CDDZ t2" +
                " where t2.ypcd=t.ypcd and t.ypxh=t1.ypxh and t.yfsb='" + mainform.yfsb + "' order by t1.PYDM";
            }
            if (var_a == 1)
            {
                comStr = "select t.ypph,t1.ypmc,t1.yfgg,t1.yfdw,t2.cdqc,t.lsjg,t.ypsl from Yf_KCMX t,yk_typk t1,YK_CDDZ t2" +
                " where t2.ypcd=t.ypcd and t.ypxh=t1.ypxh and t.yfsb='" + mainform.yfsb + "' order by t1.wbdm";
            }
            if (var_a == 2)
            {
                comStr = "select t.ypph,t1.ypmc,t1.yfgg,t1.yfdw,t2.cdqc,t.lsjg,t.ypsl from Yf_KCMX t,yk_typk t1,YK_CDDZ t2" +
                " where t2.ypcd=t.ypcd and t.ypxh=t1.ypxh and t.yfsb='" + mainform.yfsb + "' order by t1.jxdm";
            }
            dt.Load(SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null));

            DataTable dt4 = new DataTable();
            if (huizong == 0)
            {
                dt4.Clear();
                //保存 datagridView1的勾选盘点状态、行颜色、实盘数量到datatable（为了实现搜索药品在datagridView中的定位）   
                for (int i = 0; i < dataGridView1.Columns.Count - 1; i++)
                {
                    dt4.Columns.Add(i.ToString());
                }
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    DataRow dr = dt4.NewRow();
                    dt4.Rows.Add(dr);
                }
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    for (int j = 0; j < dataGridView1.Columns.Count - 1; j++)
                    {
                        if (dataGridView1.Rows[i].Cells[j].Value != null)
                        {
                            dt4.Rows[i][j] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                        }
                    }
                }

                //Yf_KCMX插到datagridView1
                dataGridView1.Rows.Clear();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    dataGridView1.Rows.Add(1);

                    for (int j = 1; j < 8; j++)
                    {
                        if (dt.Rows[i][j - 1].ToString() != "")
                        {
                            dataGridView1.Rows[i].Cells[j].Value = dt.Rows[i][j - 1].ToString();
                        }
                    }
                }
                //防止已保存的盘点单，在修改状态下的数据丢失                                    pingbi = 1;变量 防止丢失未保存的盘点单数据 
                if (lishi_b[lishi_b.Count-1].ToString()=="0")
                {
                    pingbi = 1;
                }

                //搜索完，把datatable里的勾选盘点状态、行颜色、实盘数量，对应到datagridView1
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    for (int j = 0; j < dt4.Rows.Count; j++)
                    {
                        //if (dt4.Rows[j][9]!=null)
                        //{
                            if (dataGridView1.Rows[i].Cells[1].Value.ToString() == dt4.Rows[j][1].ToString())
                            {
                                if (dt4.Rows[j][0] != null && dt4.Rows[j][0].ToString() == "True")     //对应：勾选盘点状态、行颜色
                                {
                                    dataGridView1.Rows[i].Cells[0].Value = true;
                                    dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.PaleGoldenrod;
                                }
                                dataGridView1.Rows[i].Cells[9].Value = dt4.Rows[j][9].ToString();     //对应：实盘数量
                            }
                        //}
                    }
                }
                dataGridView1.Rows[0].Selected = false;
                dataGridView1.CurrentCell=dataGridView1.Rows[0].Cells[1];
            }

            if (huizong == 1)   //按汇总按钮，才执行代码
            {
                //Yf_KCMX插到datagridView1
                dataGridView1.Rows.Clear();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    dataGridView1.Rows.Add(1);

                    for (int j = 1; j < 8; j++)
                    {
                        if (dt.Rows[i][j - 1].ToString() != "")
                        {
                            dataGridView1.Rows[i].Cells[j].Value = dt.Rows[i][j - 1].ToString();
                        }
                    }
                }
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    if (dataGridView1.Rows[i].Cells[9].Value==null)
	                {
                        dataGridView1.Rows[i].Cells[9].Value = "0";
	                }
                }
                for (int i = 0; i < dataGridView1.Columns.Count; i++)
                {
                    dataGridView1.Columns[i].ReadOnly = true;
                }
                huizong = 0;
                pingbi = 1;
            }

        }

        #region 更换搜索药品方式（拼音、五笔、角型）
        private void toolStripMenuItem2_MouseDown(object sender, MouseEventArgs e)
        {
            if (button1.Enabled==false && huizong==0)
            {
                label9.Text = "拼音代码";
                var_a = 0;
                tiaojian_huizong();
            }
        }

        private void toolStripMenuItem4_MouseDown(object sender, MouseEventArgs e)
        {
            if (button1.Enabled == false && huizong == 0)
            {
                label9.Text = "角型代码";
                var_a = 2;
                tiaojian_huizong();
            }
        }

        private void toolStripMenuItem3_MouseDown(object sender, MouseEventArgs e)
        {
            if (button1.Enabled == false && huizong == 0)
            {
                label9.Text = "五笔代码";
                var_a = 1;
                tiaojian_huizong();
            }
        }
        #endregion

        private void dataGridView2_CellClic()
        {
            //防止报错 
            if ((lishi_a.Count - 1) < dataGridView2.CurrentRow.Index)
            {
                label5.Text = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd").Replace('-', '.');
                label6.Text = "未保存";
                label7.Text = "          ";
                comStr = "select t.ygxm from GY_YGDM t where t.ygbh='" + Program.ygbh + "'";
                label8.Text = (SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null)).ToString();
                if (pingbi == 0)
                {
                    dataGridView1.Rows.Clear();
                    button1.Enabled = true;
                }
                return;
            }
            //判断如何：显示datagridView1（datagridView1内容：1已完成状态盘点单 2已保存状态盘点单 3新单）
            if (lishi_a.Count > 0 && pingbi == 0)//dataGridView2.CurrentCell != dataGridView2.Rows[dataGridView2.Rows.Count].Cells[0])
            {
                DataTable dt3 = new DataTable();
                comStr = "select t.ypph,t1.ypmc,t.ypgg,t.yfdw,t2.cdqc,t.lsjg,t.pqsl,t.spsl,t.pd_flag,t.pddh from YF_YK02 t,yk_typk t1,YK_CDDZ t2 " +
                    "where t2.ypcd=t.ypcd and t.ypxh=t1.ypxh and t.yfsb='" + mainform.yfsb + "' and t.pddh='" + lishi_a[dataGridView2.CurrentRow.Index].ToString() + "'" +
                    " order by t1.pydm";
                dt3.Load(SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null));
                dataGridView1.Rows.Clear();

                for (int i = 0; i < dt3.Rows.Count; i++)
                {
                    //查YF_YK02盘点明细表，填充datagridView1
                    dataGridView1.Rows.Add(1);
                    dataGridView1.Rows[i].Cells[9].Value = dt3.Rows[i][7].ToString();
                    for (int j = 1; j < 8; j++)
                    {
                        if (dt3.Rows[i][j - 1].ToString() != "")
                        {
                            dataGridView1.Rows[i].Cells[j].Value = dt3.Rows[i][j - 1].ToString();
                        }
                    }
                    if (dt3.Rows[i][8].ToString() == "1")   //已盘点药品：改变行颜色、打钩状态 
                    {
                        dataGridView1.Rows[i].Cells[0].Value = true;
                        dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.PaleGoldenrod;
                    }
                }

                //设置datagridView1 列的readonly                
                if (lishi_b[dataGridView2.CurrentRow.Index].ToString() == "0")   //针对已保存状态的盘点单
                {
                    for (int i = 0; i < dataGridView1.Columns.Count - 1; i++)
                    {
                        if (i == 0 || i == 8)    //打钩状态和输入数量可以edit
                        {
                            dataGridView1.Columns[i].ReadOnly = false;
                        }
                        else
                        {
                            dataGridView1.Columns[i].ReadOnly = true;
                        }
                    }
                    button5.Enabled = true;                 //按钮是否可用
                    button6.Enabled = true;

                    comStr = "select t2.pdrq,t2.wcrq,t.ygxm from GY_YGDM t,YF_YK01 t2 where t.ygbh='" + Program.ygbh + "' " +
                        "and t2.yfsb='" + mainform.yfsb + "' and t2.pddh='" + lishi_a[dataGridView2.CurrentRow.Index] + "'";
                    DataTable dt5 = new DataTable();
                    dt5.Load(SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null));  //dt5只有一行数据
                    label5.Text = Convert.ToDateTime(dt5.Rows[0][0]).ToString("yyyy-MM-dd").Replace('-', '.');
                    label6.Text = "已保存";
                    label7.Text = "          ";
                    label8.Text = dt5.Rows[0][2].ToString();
                    pddh = lishi_a[dataGridView2.CurrentRow.Index].ToString();
                }
                if (lishi_b[dataGridView2.CurrentRow.Index].ToString() == "1")  //针对已完成状态的盘点单
                {
                    for (int i = 0; i < dataGridView1.Columns.Count - 1; i++)
                    {
                        dataGridView1.Columns[i].ReadOnly = true;
                    }
                    button7.Enabled = true;                //按钮是否可用
                    comStr = "select t2.pdrq,t2.wcrq,t.ygxm from GY_YGDM t,YF_YK01 t2 where t.ygbh='" + Program.ygbh + "' " +
                        "and t2.yfsb='" + mainform.yfsb + "' and t2.pddh='" + lishi_a[dataGridView2.CurrentRow.Index] + "'";
                    DataTable dt5 = new DataTable();
                    dt5.Load(SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null));  //dt5只有一行数据
                    label5.Text = Convert.ToDateTime(dt5.Rows[0][0]).ToString("yyyy-MM-dd").Replace('-', '.');
                    label6.Text = "已完成";
                    label7.Text = Convert.ToDateTime(dt5.Rows[0][1]).ToString("yyyy-MM-dd").Replace('-', '.');
                    label8.Text = dt5.Rows[0][2].ToString();
                }
                //设置datagridView1默认不选中行
                if (dataGridView1.Rows.Count > 0)
                {
                    dataGridView1.Rows[0].Selected = false;
                }
                button1.Enabled = false;
            }
            else
            {
                button1.Enabled = true;
                dataGridView1.Rows.Clear();
            }
        }

        //dataGridView2里，点击 事件 触发的事件
        private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView2_CellClic();
        }

        /// <summary>
        /// 盘点药品搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (dataGridView1.Rows.Count > 0)
                {
                    for (int i = 0; i < dataGridView1.Rows.Count; i++)
                    {
                        if (dataGridView1.Rows[i].Cells[2].Value.ToString() == ypmc_2)
                        {
                            dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[8];
                            break;
                        }
                    }
                }
            }    
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {            
            if (dataGridView1.Rows.Count > 0)
            {
                label5.Text = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd").Replace('-', '.');
                label6.Text = "未保存";
                label7.Text = "          ";
                comStr = "select t.ygxm from GY_YGDM t where t.ygbh='" + Program.ygbh + "'";
                label8.Text = (SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null)).ToString();

                
                DataTable dt1 = new DataTable();
                dt1.Clear();
                if (var_a == 0)
                {
                    DataTable dt6 = new DataTable();
                    dt6.Clear();
                    comStr = "select t2.ypmc from yk_typk t2,Yf_KCMX t where t.ypxh=t2.ypxh and t2.pydm like '" + textBox1.Text.ToString().ToUpper() + "%'";
                    dt6.Load(SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null));
                    if (dt6.Rows.Count > 0)
                    {
                        ypmc_2 = dt6.Rows[0][0].ToString();
                    }
                }
                if (var_a == 1)
                {
                    DataTable dt6 = new DataTable();
                    dt6.Clear();
                    comStr = "select t2.ypmc from yk_typk t2,Yf_KCMX t where t.ypxh=t2.ypxh and t2.wbdm like '" + textBox1.Text.ToString().ToUpper() + "%'";
                    dt6.Load(SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null));
                    if (dt6.Rows.Count > 0)
                    {
                        ypmc_2 = dt6.Rows[0][0].ToString();
                    }
                }
                if (var_a == 2)
                {
                    DataTable dt6 = new DataTable();
                    dt6.Clear();
                    comStr = "select t2.ypmc from yk_typk t2,Yf_KCMX t where t.ypxh=t2.ypxh and t2.jxdm like '" + textBox1.Text.ToString().ToUpper() + "%'";
                    dt6.Load(SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null));
                    if (dt6.Rows.Count > 0)
                    {
                        ypmc_2 = dt6.Rows[0][0].ToString();
                    }
                }

                //for (int i = 0; i < dataGridView1.Rows.Count; i++)
                //{
                //    if (dataGridView1.Rows[i].Cells[2].Value.ToString() == ypmc_2)
                //    {
                //        dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[8];
                //        break;
                //    }
                //}
            } 
        }

        /// <summary>
        /// 完成按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否完成盘点单？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {                
                comStr = "update YF_YK01 set pdwc=1,wcrq='"+DateTime.Now.ToString()+"' where pddh='"+pddh+"'";
                SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null);
                button6.Enabled=false;
                button7.Enabled=true;               

                //7是盘前数量。9是实盘数量  rkfs rkdh yfsb 和  ckfs ckdh yfsb  
                //入库 字段    1： yfsb,rkfs,rkdh,rkrq,rkpb,czgh  2：yfsb,rkfs,rkdh,ypxh,ypcd,ypgg,yfdw,lsjg,rksl,lsje,ypph
                //出库 字段    1：yfsb,ckfs,ckdh,ckrq,ckpb,czgh   2：yfsb,ckfs,ckdh,ypxh,ypcd,ypgg,yfdw,lsjg,cksl,lsje,ypph
                //mainform.yfsb,4/4,max(rkdh)+1,wcrq,"0",program.ygbh;  mainform.yfsb,4/4,max(ckdh)+1,(2),(5),(3),(4),(6),(cha),(1)
                //float.Parse(dataGridView1.Rows[i].Cells[4].Value.ToString());

                //自动生成入库单和出库单（明细单）
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    int rkbs = 0;  //判断是否生成入库单（有盘盈）
                    int ckbs = 0;  //判断是否生成出库单（有盘亏）
                    // Math.Abs().ToString()   取绝对值
                    decimal pqsl = Convert.ToDecimal(dataGridView1.Rows[i].Cells[7].Value);
                    decimal spsl = Convert.ToDecimal(dataGridView1.Rows[i].Cells[9].Value);
                    
                    if (pqsl < spsl)   //生成入库明细单
                    {
                        decimal cha = spsl - pqsl;
                        comStr = "insert into YF_RK02(yfsb,rkfs,rkdh,ypxh,ypcd,ypgg,yfdw,lsjg,rksl,lsje,ypph) select '" + mainform.yfsb + "','4',max(rkdh)+1,"+
                            "t2.ypxh,t3.ypcd,'" + dataGridView1.Rows[i].Cells[3].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[4].Value.ToString() + "',"+
                            "'" + dataGridView1.Rows[i].Cells[6].Value.ToString() + "','" + cha + "','" + dataGridView1.Rows[i].Cells[1].Value.ToString() + "' " +
                            "from YF_RK02 t,yk_typk t2,YK_CDDZ t3 " +
                            "where t3.cdqc='"+dataGridView1.Rows[i].Cells[5].Value.ToString()+"' and t.ypmc='"+dataGridView1.Rows[i].Cells[0].Value.ToString()+"'";
                        SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null);

                        rkbs = 1;
                    }

                    if (pqsl > spsl)    //生成出库明细单
                    {
                        decimal cha = pqsl - spsl;
                        comStr = "insert into YF_cK02(yfsb,ckfs,ckdh,ypxh,ypcd,ypgg,yfdw,lsjg,cksl,lsje,ypph) select '" + mainform.yfsb + "','4',max(ckdh)+1," +
                            "t2.ypxh,t3.ypcd,'" + dataGridView1.Rows[i].Cells[3].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[4].Value.ToString() + "'," +
                            "'" + dataGridView1.Rows[i].Cells[6].Value.ToString() + "','" + cha + "','" + dataGridView1.Rows[i].Cells[1].Value.ToString() + "' " +
                            "from YF_cK02 t,yk_typk t2,YK_CDDZ t3 " +
                            "where t3.cdqc='" + dataGridView1.Rows[i].Cells[5].Value.ToString() + "' and t.ypmc='" + dataGridView1.Rows[i].Cells[0].Value.ToString() + "'";
                        SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null);

                        ckbs = 1;
                    }

                    //生成入库单
                    if (rkbs == 1)
                    {
                        comStr = "inert into YF_RK01(yfsb,rkfs,rkdh,rkrq,rkpb,czgh) select '" + mainform.yfsb + "','4',max(rkdh)+1,'" + label7.Text.ToString() + "'," +
                                "'0','" + Program.ygbh + "' from YF_RK01";
                        SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null);
                    }
                    //生成出库单
                    if ( ckbs == 1)
                    {
                        comStr = "inert into YF_cK01(yfsb,ckfs,ckdh,ckrq,ckpb,czgh) select '" + mainform.yfsb + "','4',max(ckdh)+1,'" + label7.Text.ToString() + "'," +
                                "'0','" + Program.ygbh + "' from YF_cK01";
                        SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null);
                    }
                }
                MessageBox.Show("盘点单已完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}
